/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iti.jets.gpts.beans;

import com.iti.jets.gpts.pojo.AttributeType;
import com.iti.jets.gpts.pojo.TranServiceType;
import com.iti.jets.gpts.pojo.TranServiceTypeAttribute;
import com.iti.jets.gpts.pojo.TranServiceTypeAttributeId;
import com.iti.jets.gpts.service.AttributeTypeService;
import com.iti.jets.gpts.service.ViewTransServiceTypeAtt;
import com.sun.jersey.api.client.UniformInterfaceException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
//import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;
//import org.primefaces.context.RequestContext;

/**
 *
 * @author noha
 */
@ManagedBean(name = "TSTBean")
@ViewScoped
public class AddTransportationServiceTypeBean implements Serializable {

    String attValue;
    String attributeName;
    String TSTName;
    ArrayList<TranServiceTypeAttribute> TSTAArr = new ArrayList();
    ArrayList<TranServiceTypeAttribute> beforeEdit = new ArrayList();
    int attributeId;
    String showAttributesAdded;
    JSONArray TransServJsonArr = new JSONArray();
    String addTransServ;
    DataModel<TranServiceTypeAttribute> TSattributeTypes;
    String error;
    List<AttributeType> attArray;
    List<AttributeType> attributeTypesModel;
    List<AttributeType> selectedArray = new ArrayList();

    public List<AttributeType> getAttArray() {
        return attArray;
    }

    public void setAttArray(List<AttributeType> attArray) {
        this.attArray = attArray;
    }

    public List<AttributeType> getAttributeTypesModel() {
        return attributeTypesModel;
    }

    public void setAttributeTypesModel(List<AttributeType> attributeTypesModel) {
        this.attributeTypesModel = attributeTypesModel;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public AddTransportationServiceTypeBean() {
        AttributeTypeService attservice = new AttributeTypeService();
       
        try {
            attArray = attservice.getAllAttribute();
            attributeTypesModel = attArray;
            for (int i = 0; i < attArray.size(); i++) {
                selectedArray.add(attArray.get(i));
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }
    public void updateattributeTypesModel(){
        try {
            System.out.println("================================nnnnn===============================nnnnn====================");
            AttributeTypeService attservice = new AttributeTypeService();
            attArray = attservice.getAllAttribute();
            attributeTypesModel = attArray;
            for (AttributeType at : attArray) {
                System.out.println("at "+at.getName());
            }
                        System.out.println("================================nnnnn===============================nnnnn====================");

        } catch (JSONException ex) {
            Logger.getLogger(AddTransportationServiceTypeBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    public DataModel<TranServiceTypeAttribute> getTSattributeTypes() {
      
        return TSattributeTypes;
    }

    public void setTSattributeTypes(DataModel<TranServiceTypeAttribute> TSattributeTypes) {
        this.TSattributeTypes = TSattributeTypes;
    }

    public JSONArray getTransServJsonArr() {
        return TransServJsonArr;
    }

    public void setTransServJsonArr(JSONArray TransServJsonArr) {
        this.TransServJsonArr = TransServJsonArr;
    }

    public void setAddTransServ(String addTransServ) {
        this.addTransServ = addTransServ;
    }

    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
            //Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        }
        // only got here if we didn't return false
        return true;
    }

    public void error2() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Invalid Attribute Value!"));
    }

    public void getShowAttributesAdded() {
        System.out.println("getShowAttributesAdded()");
        boolean checkflag = true;
        boolean flag = true;
        if (attValue.equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Value Field EMPTY!"));
        } else {

            boolean attNumber = isInteger(attValue);

            for (int i = 0; i < attArray.size(); i++) {
                AttributeType attObject1 = attArray.get(i);
                if (attObject1.getId() == attributeId) {
                    boolean number = attObject1.getIsNumber();
                    if (number != attNumber) {
                        System.out.println("3'alt fe attributeee");
                        checkflag = false;
                        error2();
                    }
                    break;
                }

            }

            if (checkflag == true) {
                System.out.println("sa7 fe attributeee");
                TranServiceTypeAttribute TSTAObject = new TranServiceTypeAttribute();
                TranServiceTypeAttributeId TSTAID = new TranServiceTypeAttributeId();
                TSTAID.setIdAttributeType(attributeId);
                TSTAObject.setId(TSTAID);
                TSTAObject.setValue(attValue);
                ViewTransServiceTypeAtt TSTService = new ViewTransServiceTypeAtt();
                attributeName = TSTService.getAttributeName(attributeId);

                String currentname = attributeName;
                for (int j = 0; j < TSTAArr.size(); j++) {
                    String existname = TSTAArr.get(j).getAttributeType().getName();
                    System.out.println("exist" + existname + "current" + currentname + "att" + attributeName);
                    if (existname.equals(attributeName)) {
                        error1();
                        flag = false;
                        System.out.println("da5al henaaaa");
                        break;
                    }
                    System.out.println("nohaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                }

                if (flag == true) {

                    AttributeType attObject = new AttributeType();
                    attObject.setName(attributeName);
                    attObject.setId(attributeId);
                    TSTAObject.setAttributeType(attObject);
                    TSTAArr.add(TSTAObject);
                    TSattributeTypes = new ListDataModel(TSTAArr);
                }
            }

        }

    }

    public void showMessageConfirmation() {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Confirm", "Add Done");
        RequestContext.getCurrentInstance().showMessageInDialog(message);
    }

    public void info() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Transportaion Service Added Successfully "));
    }

    public void error() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Please enter Transportation Service Name"));
    }

    public void error1() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Sry there is attribute have same name!"));
    }
    
    public void getAddTransServ() {
        boolean flag = true;
        for (int i = 0; i < TSTAArr.size() && flag == true; i++) {
            String currentname = TSTAArr.get(i).getAttributeType().getName();
            for (int j = 0; j < TSTAArr.size(); j++) {
                String existname = TSTAArr.get(j).getAttributeType().getName();
                if (i != j && existname.equals(currentname)) {
                    error1();
                    flag = false;
                    break;
                }
            }
        }
        for (int i = 0; i < TSTAArr.size() && flag == true; i++) {
            TranServiceTypeAttribute TSTAObject = TSTAArr.get(i);
            if (TSTAObject.getValue().equals("")) {
                flag = false;
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Value  Is EMPTY!"));
                break;
            } else {

                boolean attNumber = isInteger(TSTAObject.getValue());
                for (int j = 0; j < attArray.size(); j++) {
                    AttributeType attObject1 = attArray.get(j);
                    if (attObject1.getId() == TSTAObject.getAttributeType().getId()) {
                        boolean number = attObject1.getIsNumber();
                        if (number != attNumber) {
                            System.out.println("3'alt fe attributeee");
                            flag = false;
                            error2();
                        }
                        break;
                    }
                }
            }
        }
        if (flag == true) {
            if (TSTName.equals("")) {
                error();
            } else {
                try {
                    ViewTransServiceTypeAtt TSTAService = new ViewTransServiceTypeAtt();
                    ArrayList<TranServiceType> TSTAName = new ArrayList();
                    TSTAName = (ArrayList) TSTAService.getTranServiceTypes();
                    for (int i = 0; i < TSTAName.size(); i++) {
                        String TSTAname = TSTAName.get(i).getName();
                        if (TSTAname.equals(TSTName)) {
                            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "This Transportation Service Name Already exist"));
                            flag = false;
                            break;
                        }
                    }
                } catch (UniformInterfaceException ex) {
                    ex.printStackTrace();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
            }
          }
            if (flag == true) {
try {
                    JSONObject jsontranservcetype1 = new JSONObject();
                    jsontranservcetype1.put("tsname", TSTName);
                    TransServJsonArr.put(jsontranservcetype1);
                    for (int i = 0; i < TSTAArr.size(); i++) {
                        JSONObject jsontranservcetype = new JSONObject();
                        JSONObject tsta = new JSONObject();
                        tsta.put("attid", TSTAArr.get(i).getId().getIdAttributeType());
                        tsta.put("attvalue", TSTAArr.get(i).getValue());
                        jsontranservcetype.put("attributes", tsta);
                        TransServJsonArr.put(jsontranservcetype);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                ViewTransServiceTypeAtt TSTService = new ViewTransServiceTypeAtt();

                try {
                    //    try {
                    TSTService.addTranServiceType(TransServJsonArr);
                    // TSattributeTypes = new ListDataModel(TSTAArr);

                } catch (UniformInterfaceException ex) {
                    ex.printStackTrace();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                TSTAArr.clear();
                TSTName = "";
                TransServJsonArr = new JSONArray();
                info();

            }
        }
    public void setShowAttributesAdded(String showAttributesAdded) {
        this.showAttributesAdded = showAttributesAdded;
    }

    public ArrayList<TranServiceTypeAttribute> getTSTAArr() {
        return TSTAArr;
    }

    public void setTSTAArr(ArrayList<TranServiceTypeAttribute> TSTAArr) {
        this.TSTAArr = TSTAArr;
    }

    public int getAttributeId() {
        return attributeId;
    }

    public void setAttributeId(int attributeId) {
        this.attributeId = attributeId;
    }

    public String getAttValue() {
        return attValue;
    }

    public void setAttValue(String attValue) {
        this.attValue = attValue;
    }

    public String getAttributeName() {
        return attributeName;
    }

    public void setAttributeName(String attributeName) {
        this.attributeName = attributeName;
    }

    public String getTSTName() {
        return TSTName;
    }

    public void setTSTName(String TSTName) {
        this.TSTName = TSTName;
    }
//public void deleteatt()
//    {
//        TranServiceTypeAttribute TSTAEdited = TSattributeTypes.getRowData();
//         int m = TSattributeTypes.getRowIndex();
//         TSTAArr.remove(m);
//         attributeTypesModel = new ListDataModel<User>(new ListDataModel<User>(allUser););;
//    }
    public void onEdit1(RowEditEvent event) {
        TranServiceTypeAttribute TSTAEdited = TSattributeTypes.getRowData();
        System.out.println("TSTAEditeddddddd" + TSTAEdited.getAttributeType().getName() + "valuee" + TSTAEdited.getValue());
        boolean checkflag = true;
        if (TSTAEdited.getValue().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Value Field EMPTY!"));
            System.out.println("value b nulllllllllllllll");
        } else {
            boolean attNumber = isInteger(TSTAEdited.getValue());
            System.out.println("isnumber you enter" + attNumber);
            for (int i = 0; i < attArray.size(); i++) {
                AttributeType attObject1 = attArray.get(i);
                if (attObject1.getId() == attributeId) {
                    boolean number = attObject1.getIsNumber();
                    if (number != attNumber) {
                        System.out.println("3'alt fe attributeee");
                        checkflag = false;
                        error2();
                    }
                    break;
                }
            }
            if (checkflag == true) {
                System.out.println("sa7 fe attributeee");
                int m = TSattributeTypes.getRowIndex();
                System.out.println("mmm" + m);
                TSTAArr.set(m, TSTAEdited);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "attribute edited"));
            }
        }
    }

    public void onEdit(RowEditEvent event) {
        System.out.println("da5al aleditttttttttttttttttttttttttttttttt" + TSTAArr.size());
        for (int i = 0; i < TSTAArr.size(); i++) {
            System.out.println("i" + i + TSTAArr.get(i).getAttributeType().getName() + TSTAArr.get(i).getValue());
        }

        boolean checkflag = true;
        TranServiceTypeAttribute TSTAEdited = TSattributeTypes.getRowData();
        if (TSTAEdited.getValue() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error ", "Value Field EMPTY!"));
        } else {
            System.out.println("sa7 fe attributeee");
            int m = TSattributeTypes.getRowIndex();
            System.out.println("mmm" + m);
            TSTAArr.set(m, TSTAEdited);

            TranServiceTypeAttribute oldattribute = TSTAArr.get(m);
            AttributeType oldatt = oldattribute.getAttributeType();
            System.out.println("oldattrbiute" + oldatt.getName());

            attArray.add(oldatt);
            for (int i = 0; i < attArray.size(); i++) {
                System.out.println("b3d aladd" + attArray.get(i).getName());
            }
            for (int i = 0; i < attArray.size(); i++) {
                AttributeType attObject2 = attArray.get(i);
                if (attObject2.getId() == TSTAEdited.getAttributeType().getId()) {
                    System.out.println("new name" + TSTAEdited.getAttributeType().getName());
                    attArray.remove(i);
                    attributeTypesModel = attArray;
                    break;
                }
            }
            for (int i = 0; i < attArray.size(); i++) {
                System.out.println("b3d alremove" + attArray.get(i).getName());
            }
        }
    }

    public void onCancel(RowEditEvent event) {
        FacesMessage msg = new FacesMessage("Cancelled", ((TranServiceTypeAttribute) event.getObject()).getAttributeType().getName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
        System.err.println("OnCancel Hereeeeeeeeeeeeeeeeeee");
    }

}
